
import React, {useState, useRef, useEffect, useCallback} from 'react';
import {Input, Modal, List, Avatar, theme, Button, Space, Tag, Tabs, Typography, Divider, Tooltip, Image} from 'antd';
import {
    SearchOutlined,
    RobotOutlined,
    MessageOutlined,
    CloseCircleOutlined,
    EnterOutlined,
    QuestionCircleOutlined,
    RocketOutlined, TableOutlined, AlertOutlined, DownCircleFilled
} from '@ant-design/icons';

import { ConfigProvider } from 'antd';
import { ThemeConfig } from 'antd';
import logo from '@/assets/images/logo.png';
import {MessageService} from "@/utils/MessageService.ts";
import {esWrapperInstance} from "@/api/sseRequest.ts";
import MarkdownViewer from "../layout/component/Component/MarkdownViewer.tsx";
import "@/layout/component/ContentPage.css";
import "./searchAssistance.css"


const SearchAssistant = ({onSend}) => {
    const [mode, setMode] = useState('collapsed'); // collapsed | expanded | conversation
    const inputRef = useRef(null);
    const [activeTab, setActiveTab] = useState('ask');


    const [historyContent,setHistoryContent]=useState([]);
    const [curContent,setContent]=useState('');
    const [currentStreamId, setCurrentStreamId] = useState<string | null>(null);


    const onClose = () => {
        setMode('collapsed');
    }
    const setTab=()=>{
        setActiveTab(activeTab=== 'search' ? 'ask' : 'search');

    }

    //发送对话请求
    const messageService = new MessageService({
        setHistoryContent,
        setStreamId: setCurrentStreamId,
        setContent,
        esInstance: esWrapperInstance,
    });

    const handleSend = async (content: string) => {
        await messageService.send(content);
    };

    const token:ThemeConfig['token'] = {
        colorBgContainer: '#1a1a1a',        // 主容器背景（比原图更深的黑底）
        colorText: 'rgba(255,255,255,0.85)', // 主文本颜色（带透明度白字）
        colorTextHeading: '#ffffff',         // 标题文字（纯白）
        colorTextPlaceholder: '#ffffff',     // 输入框提示文字（中灰色）
        colorPrimary: '#0861c2',             // 主色（保持原图蓝色）
        colorPrimaryBg: 'rgba(24,144,255,0.1)', // 功能项背景（透明蓝底）
        colorBgElevated: '#2a2a2a',          // 悬浮面板背景（深灰）
        colorBorder: '#434343',              // 边框颜色（适配深色）
        colorTextSecondary: '#ffffff',       // 次要文字（浅灰）
        colorTextDisabled: '#4d4d4d',       // 禁用状态文字（深灰）
        boxShadowSecondary: '0 2px 8px rgba(255,255,255,0.1)', // 阴影（适配深色模式）
        colorBgLayout: '#141414',            // 布局背景（最深层黑）
    };

    // 模拟搜索建议
    const FEATURES = [
        {
            title: "Web 开发指导",
            description: "现代 Web 开发概念与最佳实践解答，涵盖架构设计到部署优化"
        },
        {
            title: "代码示例库",
            description: "提供 JavaScript/Python 等多种语言的代码片段，支持实时执行演示"
        },
        {
            title: "React/Next.js 专家",
            description: "组件设计、状态管理、服务端渲染等场景的完整解决方案"
        },
        {
            title: "调试支持",
            description: "代码错误诊断、性能分析、异常追踪的智能化辅助"
        },
        {
            title: "算法解析",
            description: "数据结构与算法可视化解释，LeetCode 解题思路分析"
        },
        {
            title: "优化建议",
            description: "无障碍访问、性能优化、安全加固的专业指导方案"
        }
    ];

    // 样式配置
    const styles = {
        //固定再右下底部
        container: {
            minHeight: '0',
            // position: 'fixed',
            // right: 24,
            // bottom: 24,
            // zIndex: 1000
        },
        //collapsed形态
        collapsedInput: {
            // width: 170,
            backgroundColor: "#001529",
            // border: `1px solid ${token.colorBorder}`,
            borderRadius: 8,
            color: '#d0cccc',

            // 添加悬停状态
            '&:hover': {
                borderColor: 'rgb(0,21,41)'  // 悬停时边框变亮
            },
            // 添加聚焦状态
            '&:focus': {
                boxShadow: '0 0 0 2px rgba(255, 255, 255, 0.2)'  // 聚焦时光晕效果
            }
        },
        featureBadge: {
            width: 32,
            height: 32,
            borderRadius: token.borderRadius,
            background: token.colorPrimaryBg,
            color: token.colorPrimary,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            fontWeight: token.fontWeightStrong
        },
        messageCard: {
            position: 'relative',
            '&:hover': {
                '& $actionBar': {
                    opacity: 1
                }
            }
        },
        actionBar: {
            position: 'absolute',
            right: -40,
            top: 0,
            opacity: 0,
            transition: 'opacity 0.3s',
            button: {
                marginBottom: 4
            }
        },

        gridContainer: {
            display: 'grid',
            width: '100%',
            gridTemplateColumns: "repeat(7, minmax(80px, 1fr))",
            gridTemplateRows: 'repeat(3, minmax(80px, 1fr))',
            gap: '16px',

        },
        newsCard: {
            background: token.colorBgElevated,
            borderRadius:6,
            padding: 16,
            border: `1px solid ${token.colorBorderSecondary}`,
            cursor: 'pointer',
            transition: 'all 0.3s',
            gridRow: 1,/* 占据第一行 */
            gridColumn: "3/6",
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
        },
        quesCard: {
            background: token.colorBgContainer,
            padding: 24,
            textAlign: 'center',
            border: `1px dashed ${token.colorBorder}`,// 使用虚线边框
            gridRow: "2/4",
            gridColumn: "span 3",
            display: 'flex',
            flexDirection: 'column',
            justifyContent: 'center',
            alignItems: 'center',

        },
        specialCard: {
            background: token.colorPrimaryBg,
            borderRadius: 8,
            padding: 24,
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            gridColumn: "span 4",
        },
        cardHeader: {
            display: 'flex',
            alignItems: 'center',
            marginBottom: 8
        },
        fileIcon: {
            fontSize: 18,
            color: token.colorPrimary,
            marginRight: 8
        },
        quesIcon: {
            fontSize: 24,
            color: token.colorWarning,
            marginBottom: 12
        },
        specialIcon: {
            fontSize: 28,
            color: token.colorPrimary,
            marginBottom: 16
        },
        cardTitle: {
            fontSize: 15,
            color: token.colorTextHeading
        },
        fileName: {
            display: 'block',
            fontSize: 13,
            color: token.colorTextSecondary
        },
        contentText: {
            fontSize: 14,
            color: token.colorText
        },
        specialTitle: {
            textAlign: 'center',
            margin: 0,
            color: token.colorPrimaryText
        }
    }

    // 滚动容器引用
    const scrollContainerRef = useRef<HTMLDivElement>(null)
    // 底部锚点引用
    const messagesEndRef = useRef<HTMLDivElement>(null)
    // 是否显示锚点
    const [showAnchor, setShowAnchor] = useState(false)
    // 滚动阈值（距离底部 200px 触发）
    const SCROLL_THRESHOLD = 20


    // 滚动到底部方法
    const scrollToBottom = use


    Callback((behavior: ScrollBehavior = 'smooth') => {
        messagesEndRef.current?.scrollIntoView({ behavior })
    }, [])

    // 检测滚动位置
    const handleScroll = useCallback(() => {
        const container = scrollContainerRef.current
        if (!container) return

        // 计算是否接近底部
        const { scrollTop, clientHeight, scrollHeight } = container
        const isNearBottom = scrollTop + clientHeight < scrollHeight - SCROLL_THRESHOLD

        setShowAnchor(isNearBottom)
    }, [])

    // 初始化滚动监听
    useEffect(() => {
        const container = scrollContainerRef.current
        if (!container) return

        container.addEventListener('scroll', handleScroll)
        return () => container.removeEventListener('scroll', handleScroll)
    }, [handleScroll])

    // 内容更新时自动检测位置
    useEffect(() => {
        handleScroll()
        scrollToBottom('auto')
    }, [handleScroll, scrollToBottom])


    // 使用 useEffect 监听内容变化
    useEffect(() => {
        if (scrollContainerRef.current) {
            scrollContainerRef.current.scrollTo({
                top: scrollContainerRef.current.scrollHeight,
                behavior: 'smooth'
            });
        }
    }, [historyContent]); // 当对话内容更新时触发



    return (
        <ConfigProvider theme={{
            token: token,
            components: {
                Input: {
                    colorTextPlaceholder: '#ffffff', // 全局placeholder颜色
                },
            },
        }}>
            <div style={styles.container}>
                <Input
                    placeholder="Search..."
                    prefix={<SearchOutlined/>}
                    style={styles.collapsedInput}
                    onFocus={() => setMode('conversation')}
                />

                {mode === 'conversation' && (
                    <Modal
                        width={800}
                        open={true}
                        footer={null}
                        closable={false}
                        bodyStyle={{
                            padding: 0,
                            background: token.colorBgContainer,
                            borderRadius: token.borderRadiusLG,
                            minHeight: '75vh',
                            maxHeight: '75vh',
                            display: 'flex',
                            flexDirection: 'column',
                            overflow: 'hidden' // 防止内容溢出外层

                        }}
                    >
                        {/* 增强的头部导航 */}
                        <div style={{
                            display: 'flex',
                            alignItems: 'center',
                            padding: '12px 24px',
                            borderBottom: `1px solid ${token.colorBorder}`,
                            background: token.colorBgElevated
                        }}>
                            <Tabs
                                activeKey={activeTab}
                                onChange={setTab}
                                tabBarStyle={{margin: 0}}
                                items={[
                                    {
                                        label: (
                                            <span>
                                <SearchOutlined/>
                                <span style={{marginLeft: 8}}>历史记录</span>
                              </span>
                                        ),
                                        key: 'search'
                                    },
                                    {
                                        label: (
                              <span>
                                <MessageOutlined/>
                                <span style={{marginLeft: 8}}>对话</span>
                              </span>
                                        ),
                                        key: 'ask'
                                    }
                                ]}
                            />
                            <Tag
                                color="white"
                                icon={<CloseCircleOutlined />}
                                style={{
                                    marginLeft: 'auto',
                                    background: 'transparent',
                                    borderColor: token.colorPrimary,
                                    height:20,
                                    bottom:0,
                                }}
                                onClick={() => setMode('collapsed')}
                            >
                                关闭
                            </Tag>
                        </div>

                        {/* 智能输入区域 */}
                        <div style={{
                            borderTop: `1px solid ${token.colorBorder}`,
                            padding: 16,
                            background: token.colorBgLayout,
                            display: 'flex',
                            alignItems: 'center',

                        }}>

                            <Input
                                autoSize={{minRows: 1, maxRows: 6}}
                                value={curContent}
                                onChange={(e) => setContent(e.target.value)}
                                onPressEnter={()=>handleSend(curContent)}
                                placeholder={activeTab === "search" ? "Search History Conversation..." : "Ask Me Anything..."}
                                style={{
                                    background: token.colorBgContainer,
                                    borderRadius: token.borderRadiusLG,
                                    padding: '12px 16px'
                                }}
                                allowClear
                                suffix={
                                    <EnterOutlined style={{
                                        fontSize: 16,
                                        color: '#1677ff',}}
                                        onClick={()=>handleSend(curContent)}
                                    />
                                }
                            />
                        </div>

                        {/* 智能内容区域 */}
                        <div
                            ref={scrollContainerRef}
                            style={{
                            flex: 1,
                            display: 'absolute',
                            flexDirection: "column",
                            padding: 20,
                            position: 'relative',
                        }}
                         className="scroll-container"
                        >
                            {activeTab === "search" ? (
                                // 初始引导界面
                                <div style={{maxWidth: 720, flex:1}}>
                                    <Typography.Title level={4} style={{color: token.colorTextHeading}}>
                                        <RobotOutlined style={{marginRight: 8}}/>
                                        Search History Conversation
                                    </Typography.Title>

                                    <Divider style={{color: token.colorTextSecondary}}></Divider>

                                    <List
                                        itemLayout="horizontal"
                                        dataSource={FEATURES}
                                        renderItem={(item, index) => (
                                            <List.Item style={{border: 0, padding: '8px 0'}}>
                                                <List.Item.Meta
                                                    avatar={
                                                        <div style={styles.featureBadge}>
                                                            #{index + 1}
                                                        </div>
                                                    }
                                                    title={<Typography.Text strong>{item.title}</Typography.Text>}
                                                    description={
                                                        <Typography.Text type="secondary" style={{color:token.colorText}}>
                                                            {item.description}
                                                        </Typography.Text>
                                                    }
                                                />
                                            </List.Item>
                                        )}
                                    />
                                </div>
                            ) : (
                                // 对话消息流
                                <div style={{maxWidth: 760, flex: 1, minHeight:0}}>
                                    {historyContent.length === 0 ? (
                                        <div style={styles.gridContainer}>
                                            {/* 标题卡片1 */}
                                            <div style={styles.newsCard}>
                                                <img
                                                    src={logo}
                                                    alt={"logo"}
                                                    style={{
                                                        width: '80%',
                                                        height: 'auto',
                                                        maxHeight: '80%',
                                                    }}
                                                />
                                            </div>

                                            {/* 侧边卡片 */}
                                            <div style={styles.quesCard}>
                                                <QuestionCircleOutlined style={styles.quesIcon}/>
                                                <Typography.Text strong style={styles.cardTitle}>
                                                    死亡真的是无法避免的吗？
                                                </Typography.Text>
                                            </div>

                                            {/* 特色卡片1 */}
                                            <div style={styles.specialCard}>
                                                <RocketOutlined style={styles.specialIcon}/>
                                                <Typography.Title level={5} style={styles.specialTitle}>
                                                    30岁重启人生！化身乐队吉他手
                                                </Typography.Title>
                                            </div>

                                            {/* 特色卡片2 */}
                                            <div style={styles.specialCard}>
                                                <TableOutlined style={styles.specialIcon}/>
                                                <Typography.Title level={5} style={styles.specialTitle}>
                                                    用表格归纳总结基层工作者心声
                                                </Typography.Title>
                                            </div>
                                        </div>
                                    ) : (
                                        <>
                                            {historyContent.map((message) => (
                                                <div key={message.id} className={`message ${message.author}`}>
                                                    {message.author === 'Assistance' && (
                                                        <div className="bot-avatar">
                                                            <img src="/logo512.png" alt="Bot Avatar" />
                                                        </div>
                                                    )}
                                                    <div className="message-content">
                                                        <MarkdownViewer markdownData={message.text} />
                                                    </div>
                                                </div>
                                            ))}

                                             {/*滚动锚点 */}
                                            <div ref={messagesEndRef} />
                                        </>
                                    )}
                                </div>
                            )}
                        </div>
                        {showAnchor && (
                            <DownCircleFilled
                                style={{
                                    position: 'absolute',
                                    right: 24,
                                    bottom: 24,
                                    fontSize: 32,
                                    color: '#1890ff',
                                    cursor: 'pointer',
                                    boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
                                    borderRadius: '50%',
                                    transition: 'opacity 0.3s',
                                    zIndex: 100,
                                }}
                                onClick={() => scrollToBottom()}
                            />
                        )}
                    </Modal>
                )}
            </div>
        </ConfigProvider>
    );
}

export default SearchAssistant;